package com.heima.comment.service.impl;

import com.heima.comment.dto.CommentRepayDto;
import com.heima.comment.dto.CommentRepayLikeDto;
import com.heima.comment.dto.CommentRepaySaveDto;
import com.heima.comment.entity.ApComment;
import com.heima.comment.entity.ApCommentRepayLike;
import com.heima.comment.entity.ApCommentReply;
import com.heima.comment.entity.ApUser;
import com.heima.comment.feign.UserFeign;
import com.heima.comment.service.ICommentReplyService;
import com.heima.common.aliyun.GreenTextScan;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.AppThreadLocalUtil;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class CommentReplyServiceImpl implements ICommentReplyService {

    @Autowired
    private GreenTextScan textScan;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private UserFeign userFeign;

    // 保存评论的回复
    @Override
    public ResponseResult save(CommentRepaySaveDto dto) {

        // 判断
        if (dto == null){

            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        // 获取请求参数
        String commentId = dto.getCommentId();
        String content = dto.getContent();

        // 获取用户id
        User user = AppThreadLocalUtil.get();

        // 判断用户登录方式
        if (user == null){

            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        // 判断
        if (content.length() > 140){

            return ResponseResult.errorResult(402,"评论内容不能超过140字");
        }

        ApCommentReply apCommentReply = new ApCommentReply();

        try {
            // 评论回复审核
            Map map = textScan.greenTextScan(content);

            // 判断结果
            String suggestion = (String) map.get("suggestion");

            switch (suggestion) {
                case "pass":

                    // 审核通过
                    // 1.构造保存对象

                    Integer userId = user.getUserId();
                    String name = user.getName();

                    // 通过评论id查询文章id
                    ApComment apComment = mongoTemplate.findById(new ObjectId(commentId), ApComment.class);
                    Long entryId = apComment.getEntryId();

                    // 通过userId查询头像
                    ResponseResult<ApUser> result = userFeign.selectUser(userId);

                    if (result.getCode().equals(AppHttpCodeEnum.SUCCESS.getCode())){

                        // 封装数据
                        apCommentReply.setAuthorId(userId);
                        apCommentReply.setAuthorName(name);
                        apCommentReply.setEntryId(entryId);
                        apCommentReply.setCommentId(commentId);
                        apCommentReply.setContent(content);
                        apCommentReply.setImage(result.getData().getImage());
                        apCommentReply.setCreatedTime(new Date());

                        // 保存到评论回复表
                        mongoTemplate.save(apCommentReply);

                        // 更新评论表的回复数
                        Integer reply = apComment.getReply();
                        reply = ++reply;
                        apComment.setReply(reply);
                        mongoTemplate.save(apComment);
                    }


                    break;
                case "block":
                    // 审核不通过
                    return ResponseResult.errorResult(402,"审核失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseResult.okResult(apCommentReply);
    }

    // 查询回复列表
    @Override
    public ResponseResult load(CommentRepayDto dto) {

        // 判断
        if (dto == null){

            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        // 获取请求参数
        String commentId = dto.getCommentId();
        Date minDate = dto.getMinDate();
        Long page = dto.getPage();
        Integer size = dto.getSize();

        // 指定查询条件
        Criteria criteria = Criteria.where("commentId").is(commentId).and("createdTime").lt(minDate);
        Query query = Query.query(criteria).skip((page - 1) * size).limit(size).with(Sort.by(Sort.Order.desc("createdTime")));

        // 查询
        List<ApCommentReply> apCommentReplies = mongoTemplate.find(query, ApCommentReply.class);

        List<ApCommentReply> commentReplyList = new ArrayList<>();

        // 判断是否对回复进行点赞
        // 循环遍历
        for (ApCommentReply apCommentReply : apCommentReplies) {

            // 获取回复id
            String ReplyId = apCommentReply.getId();

            // 获取用户id
            Integer userId = AppThreadLocalUtil.get().getUserId();
            if (userId != null){

                // 指定查询条件
                Criteria criteria1 = Criteria.where("authorId").is(userId).and("commentRepayId").is(ReplyId);

                // 查询
                ApCommentRepayLike repayLike = mongoTemplate.findOne(Query.query(criteria1), ApCommentRepayLike.class);

                // 判断
                if (repayLike != null && repayLike.getOperation() == 0){

                    apCommentReply.setOperation(0);
                }

                commentReplyList.add(apCommentReply);

            }

        }

        return ResponseResult.okResult(commentReplyList);
    }


    // 回复点赞
    @Override
    public ResponseResult like(CommentRepayLikeDto dto) {

        // 获取用户id
        Integer userId = AppThreadLocalUtil.get().getUserId();

        if (userId == null){

            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        if (dto == null){

            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        // 获取请求参数
        String repayId = dto.getCommentRepayId();
        Short operation = dto.getOperation();

        // 查询是否已经点赞
        // 1.指定查询条件
        Criteria criteria = Criteria.where("authorId").is(userId).and("commentRepayId").is(repayId);

        // 2.查询
        ApCommentRepayLike repayLike = mongoTemplate.findOne(Query.query(criteria), ApCommentRepayLike.class);

        // 3.判断
        if (repayLike == null && operation == 0){

            // 保存点赞数据
            ApCommentRepayLike commentRepayLike = new ApCommentRepayLike();
            commentRepayLike.setAuthorId(userId);
            commentRepayLike.setCommentRepayId(repayId);
            commentRepayLike.setOperation(0);
            mongoTemplate.save(commentRepayLike);

            // 更新回复表点赞数量
            updataReplyLikes(repayId,operation);


        }

        if (repayLike != null && !repayLike.getOperation().toString().equals(operation.toString())){

            // 更新点赞表
            Update update = new Update();
            update.set("operation",operation);
            mongoTemplate.updateFirst(Query.query(criteria),update,ApCommentRepayLike.class);

            // 更新回复表点赞数量
            updataReplyLikes(repayId,operation);
        }



        return ResponseResult.okResult();
    }

    private void updataReplyLikes(String repayId, Short operation) {

        // 更新回复表点赞数量
        ApCommentReply commentReply = mongoTemplate.findById(new ObjectId(repayId), ApCommentReply.class);
        Long likes = commentReply.getLikes();

        if (operation == 0){
            likes = ++likes;
        }else if (operation == 1){
            likes = --likes;
        }

        commentReply.setLikes(likes);
        mongoTemplate.save(commentReply);
    }
}
